const express = require('express');
const { auth, checkRole } = require('../middleware/auth');
const { getConnection } = require('../config/database');

const router = express.Router();

// 获取用户信息
router.get('/profile', auth, async (req, res) => {
  try {
    const connection = await getConnection();
    
    const [users] = await connection.execute(
      'SELECT id, username, email, role, monthly_usage, created_at FROM users WHERE id = ?',
      [req.user.id]
    );

    if (users.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }

    const user = users[0];

    // 获取用户订阅信息
    const [subscriptions] = await connection.execute(
      'SELECT * FROM subscriptions WHERE user_id = ? AND status = "active" ORDER BY created_at DESC LIMIT 1',
      [req.user.id]
    );

    res.json({
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        monthlyUsage: user.monthly_usage,
        createdAt: user.created_at,
        subscription: subscriptions.length > 0 ? subscriptions[0] : null
      }
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ error: '获取用户信息失败' });
  }
});

// 更新用户信息
router.put('/profile', auth, async (req, res) => {
  try {
    const { username, email } = req.body;
    const connection = await getConnection();

    // 检查用户名是否已被其他用户使用
    if (username) {
      const [existingUsers] = await connection.execute(
        'SELECT id FROM users WHERE username = ? AND id != ?',
        [username, req.user.id]
      );

      if (existingUsers.length > 0) {
        return res.status(400).json({ error: '用户名已被使用' });
      }
    }

    // 检查邮箱是否已被其他用户使用
    if (email) {
      const [existingUsers] = await connection.execute(
        'SELECT id FROM users WHERE email = ? AND id != ?',
        [email, req.user.id]
      );

      if (existingUsers.length > 0) {
        return res.status(400).json({ error: '邮箱已被使用' });
      }
    }

    // 构建更新查询
    const updates = [];
    const params = [];

    if (username) {
      updates.push('username = ?');
      params.push(username);
    }

    if (email) {
      updates.push('email = ?');
      params.push(email);
    }

    if (updates.length === 0) {
      return res.status(400).json({ error: '没有要更新的信息' });
    }

    params.push(req.user.id);

    await connection.execute(
      `UPDATE users SET ${updates.join(', ')} WHERE id = ?`,
      params
    );

    res.json({ message: '用户信息更新成功' });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({ error: '更新用户信息失败' });
  }
});

// 获取用户使用统计
router.get('/stats', auth, async (req, res) => {
  try {
    const connection = await getConnection();

    // 获取总处理次数
    const [totalResult] = await connection.execute(
      'SELECT COUNT(*) as total FROM processing_history WHERE user_id = ?',
      [req.user.id]
    );

    // 获取本月处理次数
    const [monthlyResult] = await connection.execute(
      'SELECT COUNT(*) as monthly FROM processing_history WHERE user_id = ? AND MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())',
      [req.user.id]
    );

    // 获取处理历史
    const [historyResult] = await connection.execute(
      'SELECT * FROM processing_history WHERE user_id = ? ORDER BY created_at DESC LIMIT 10',
      [req.user.id]
    );

    // 获取任务统计
    const [taskStats] = await connection.execute(
      'SELECT status, COUNT(*) as count FROM tasks WHERE user_id = ? GROUP BY status',
      [req.user.id]
    );

    res.json({
      stats: {
        totalProcessed: totalResult[0].total,
        monthlyProcessed: monthlyResult[0].monthly,
        currentUsage: req.user.monthly_usage
      },
      recentHistory: historyResult,
      taskStats: taskStats
    });
  } catch (error) {
    console.error('获取用户统计错误:', error);
    res.status(500).json({ error: '获取用户统计失败' });
  }
});

// 获取处理历史
router.get('/history', auth, async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;
    
    const connection = await getConnection();

    const [history] = await connection.execute(
      'SELECT ph.*, t.task_type, t.original_file, t.processed_file FROM processing_history ph LEFT JOIN tasks t ON ph.task_id = t.id WHERE ph.user_id = ? ORDER BY ph.created_at DESC LIMIT ? OFFSET ?',
      [req.user.id, parseInt(limit), offset]
    );

    // 获取总数
    const [countResult] = await connection.execute(
      'SELECT COUNT(*) as total FROM processing_history WHERE user_id = ?',
      [req.user.id]
    );

    res.json({
      history: history.map(item => ({
        id: item.id,
        fileName: item.file_name,
        fileSize: item.file_size,
        processingTime: item.processing_time,
        taskType: item.task_type,
        originalFile: item.original_file ? `/uploads/${item.original_file}` : null,
        processedFile: item.processed_file ? `/uploads/${item.processed_file}` : null,
        createdAt: item.created_at
      })),
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: countResult[0].total,
        pages: Math.ceil(countResult[0].total / limit)
      }
    });
  } catch (error) {
    console.error('获取处理历史错误:', error);
    res.status(500).json({ error: '获取处理历史失败' });
  }
});

// 升级用户角色（管理员功能）
router.put('/upgrade/:userId', auth, checkRole(['premium', 'enterprise']), async (req, res) => {
  try {
    const { userId } = req.params;
    const { role, planType } = req.body;
    
    if (!['free', 'premium', 'enterprise'].includes(role)) {
      return res.status(400).json({ error: '无效的用户角色' });
    }

    const connection = await getConnection();

    // 更新用户角色
    await connection.execute(
      'UPDATE users SET role = ? WHERE id = ?',
      [role, userId]
    );

    // 如果是付费用户，创建订阅记录
    if (role !== 'free' && planType) {
      const endDate = new Date();
      if (planType === 'monthly') {
        endDate.setMonth(endDate.getMonth() + 1);
      } else if (planType === 'yearly') {
        endDate.setFullYear(endDate.getFullYear() + 1);
      }

      await connection.execute(
        'INSERT INTO subscriptions (user_id, plan_type, end_date) VALUES (?, ?, ?)',
        [userId, planType, endDate]
      );
    }

    res.json({ message: '用户角色升级成功' });
  } catch (error) {
    console.error('升级用户角色错误:', error);
    res.status(500).json({ error: '升级用户角色失败' });
  }
});

// 重置用户使用量（管理员功能）
router.put('/reset-usage/:userId', auth, checkRole(['premium', 'enterprise']), async (req, res) => {
  try {
    const { userId } = req.params;
    const connection = await getConnection();

    await connection.execute(
      'UPDATE users SET monthly_usage = 0 WHERE id = ?',
      [userId]
    );

    res.json({ message: '用户使用量重置成功' });
  } catch (error) {
    console.error('重置用户使用量错误:', error);
    res.status(500).json({ error: '重置用户使用量失败' });
  }
});

// 删除用户（管理员功能）
router.delete('/:userId', auth, checkRole(['enterprise']), async (req, res) => {
  try {
    const { userId } = req.params;
    const connection = await getConnection();

    // 删除用户相关的所有数据
    await connection.execute('DELETE FROM processing_history WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM subscriptions WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM tasks WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM users WHERE id = ?', [userId]);

    res.json({ message: '用户删除成功' });
  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({ error: '删除用户失败' });
  }
});

module.exports = router; 